package cn.newgrand.netcall.consultant;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.TimerTask;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.jivesoftware.MainWindow;
import org.jivesoftware.RestFulService;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.RolloverButton;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomButton;
import org.jivesoftware.spark.ui.ChatRoomListenerAdapter;
import org.jivesoftware.spark.ui.CommandPanel;
import org.jivesoftware.spark.util.BrowserLauncher;
import org.jivesoftware.spark.util.Encryptor;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.alerts.SparkToaster;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;

import com.install4j.api.launcher.StartupNotification;

import cn.newgrand.common.NetcallUtil;
import cn.newgrand.netcall.consultant.ui.MessageCenterPanel;
import cn.newgrand.netcall.consultant.ui.PollPanel;
import cn.newgrand.netcall.consultant.ui.SpecialistList;
import cn.newgrand.netcall.consultant.ui.SpecialistSearchForm;
import cn.newgrand.smackx.consultant.ConsultantManager;
import cn.newgrand.smackx.consultant.packet.SpecialistNotifyPacket;
import cn.newgrand.smackx.consultant.packet.SpecialistPollPacket;
import cn.newgrand.smackx.specialist.ExpertManager;

public class ConsultantPlugin implements Plugin ,PacketListener{

	private ConsultantManager consultantManager;
	private SpecialistList sp;
	private SearchManager searchManager;
	//private Map<String,NotifyWindow> toasters = new HashMap<String,NotifyWindow>();
	@Override
	public void initialize() {
		
		addButoon();
		LocalPreferences preferences = SettingsManager.getLocalPreferences();
        if(!preferences.isPublicLogin()){
        	return;
        }
		
		StartupNotification.registerStartupListener(new NetcallStartupListener());
		TaskEngine.getInstance().schedule(new TimerTask() {
            public void run() {
            	URLConsultantManager.handleURIMapping(Spark.ARGUMENTS);
            }
        }, 2000);
		
		// TODO Auto-generated method stub
		consultantManager = ConsultantManager.getInstance(SparkManager.getConnection());
		consultantManager.initialize();
		
		RolloverButton searchSpecialist = new RolloverButton(SparkRes.getImageIcon(SparkRes.SEARCH_USER_16x16));
		searchSpecialist.setToolTipText("搜索专家");
		SparkManager.getWorkspace().getCommandPanel().add(searchSpecialist,1);
		searchSpecialist.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				SpecialistSearchForm form = new SpecialistSearchForm();
		        //JFrame frame = new JFrame();
		        //frame.setIconImage(SparkRes.getImageIcon(SparkRes.VIEW_IMAGE).getImage());
		        final JDialog dialog = new JDialog(SparkManager.getMainWindow(), "搜索专家", false);
		        
		        dialog.getContentPane().add(form);
		        dialog.pack();
		        dialog.setSize(600, 600);

		        GraphicUtils.centerWindowOnScreen(dialog);
		        dialog.setVisible(true);
			}
			
		});
		
		sp = new SpecialistList();
		sp.initialize();
		
		searchManager = new SearchManager();
		
		PacketFilter filter = new PacketTypeFilter(SpecialistNotifyPacket.class);
		SparkManager.getConnection().addPacketListener(this, filter);
		
		PacketFilter filter2 = new PacketTypeFilter(SpecialistPollPacket.class);
		PollPacketListener poll = new PollPacketListener();
		SparkManager.getConnection().addPacketListener(poll, filter2);
		
		SparkManager.getChatManager().addChatRoomListener(new ChatRoomListenerAdapter(){
			public void chatRoomOpened(final ChatRoom room){
				if(ExpertManager.getInstance(SparkManager.getConnection()).isExpert()){
					String iconURI ="images/question.gif";
					URL imageURL =ConsultantPlugin.class.getClassLoader().getResource(iconURI);
					ChatRoomButton  noteQuestionButton = new ChatRoomButton("",new ImageIcon(imageURL));
					noteQuestionButton.setToolTipText("添加常见问题");
					noteQuestionButton.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent arg0) {
							try {
								String logonguid = toHexString(encrypt(
										LocalPreferences.getTokenKey(),
										SparkRes.getString("DESKEY")));
								String server = SettingsManager.getLocalPreferences().getKeyValue("channelname");
								String username = SettingsManager.getLocalPreferences().getKeyValue("userField"+server); 	
								String logonname = toHexString(encrypt(username,
											SparkRes.getString("DESKEY")));
								String servername = SettingsManager
										.getLocalPreferences().getServername();
								String returnurl = "http://www.netcall.cc/netcall/ProblemAdd.aspx";
								returnurl = toHexString(encrypt(returnurl,
										SparkRes.getString("DESKEY")));				 	
								String urlstring = "http://uia.netcall.cc:80/SetCookie.aspx?"+"&lg="+logonguid+"&ln="+logonname+"&ru="+returnurl;	
								BrowserLauncher.openURL(urlstring);
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
					room.getToolBar().addChatRoomButton(noteQuestionButton);				    
				}
			} 
		});
	}

	@Override
	public void shutdown() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean canShutDown() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void uninstall() {
		// TODO Auto-generated method stub
		
	}

	public ConsultantManager getConsultantManager(){
		return consultantManager;
	}
	
	public SpecialistList getSpecialistList(){
		return sp;
	}
	
	public SearchManager getSearchManager(){
		return searchManager;
	}
	
	@Override
	public void processPacket(final Packet packet) {
		// TODO Auto-generated method stub
        final SpecialistNotifyPacket iq = (SpecialistNotifyPacket)packet;
        
		if(!iq.getStatus().equals("start")&&!iq.getStatus().equals("over")){
			return;
		}
		
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    //NotifyWindow toaster;
                	
                    if(iq.getStatus().equals("start")){
                    	//if(!toasters.containsKey(iq.getSpid())){//是否有服务端来触发再次显示通知框。通知框被点x关闭的情况，并没有退出咨询
//                    		toaster = new NotifyWindow(iq.getSpjid(),iq.getSpid());
//                    		
//		                    toaster.setBorder(BorderFactory.createBevelBorder(0));
//		                    toaster.setTitle(Res.getString("title.notification"));
//		                    toaster.showToaster(iq.getTitle());
//		                    toasters.put(iq.getSpid(), toaster);
                    	//}
                        SparkToaster toaster = new SparkToaster();
                        toaster.setNotifyShowForever(false);
                        toaster.setDisplayTime(20000);
                        toaster.setBorder(BorderFactory.createBevelBorder(0));
                        toaster.setTitle(Res.getString("title.notification"));
                        toaster.setViewLabelString("加入");
                        toaster.setHidable(true);
                        toaster.setCustomAction(new AbstractAction() {
							
							@Override
							public void actionPerformed(ActionEvent e) {
								// TODO Auto-generated method stub
								if(MessageCenterPanel.getInstance().isHasSpecialistMessage(iq.getSpid())){
									String spBarejid = StringUtils.parseBareAddress(iq.getSpjid());
				                    ChatRoom chatRoom = SparkManager.getChatManager().createChatRoom(spBarejid, iq.getSpid(), iq.getSpid());
				                    SparkManager.getChatManager().getChatContainer().activateChatRoom(chatRoom);
				                    MessageCenterPanel.getInstance().getJoinMessageItem(iq.getSpid()).flagStarted();
								}
							}
						});
                        toaster.showToaster(iq.getSpid()+"专家队列已到达，可以开始咨询了。");

                        MessageCenterPanel.getInstance().addJoinMessageItem("专家:"+iq.getSpid(), iq.getSpjid(), iq.getSpid());
                        
                    }else if(iq.getStatus().equals("over")&&iq.getResult().equals("timeout")){
//                    	toaster = toasters.get(iq.getSpid());
//                    	if(toaster.getWindow()!=null&&toaster.getWindow().isVisible())
//                    		toaster.closeWindow();
//                    	 toasters.remove(toasters.get(iq.getSpid()));
                        SparkToaster toaster = new SparkToaster();
                        toaster.setNotifyShowForever(false);
                        toaster.setDisplayTime(20000);
                        toaster.setBorder(BorderFactory.createBevelBorder(0));
                        toaster.setTitle(Res.getString("title.notification"));
                        toaster.setViewLabelString("");
                        //toaster.showToaster(iq.getTitle());
                        
                    	MessageCenterPanel.getInstance().removeJoinMessageItem(iq.getSpid(), iq.getSpjid());
                    	SpecialistQueueManager.getInstance().removeWhenLeave(iq.getSpjid());
                		JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "超时退出聊天");
                    }else if(iq.getStatus().equals("over")&&iq.getResult().equals("forceclose")){
//                    	toaster = toasters.get(iq.getSpid());
//                    	if(toaster.getWindow()!=null&&toaster.getWindow().isVisible())
//                    		toaster.closeWindow();
//                    	 toasters.remove(toasters.get(iq.getSpid()));
                        SparkToaster toaster = new SparkToaster();
                        toaster.setNotifyShowForever(false);
                        toaster.setDisplayTime(20000);
                        toaster.setBorder(BorderFactory.createBevelBorder(0));
                        toaster.setTitle(Res.getString("title.notification"));
                        toaster.setViewLabelString("");
                        //toaster.showToaster(iq.getTitle());
                        SpecialistQueueManager.getInstance().removeWhenLeave(iq.getSpjid());
                    	MessageCenterPanel.getInstance().removeJoinMessageItem(iq.getSpid(), iq.getSpjid());
                		JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "专家已注销");
                    }else if("over".equals(iq.getStatus()) && "expertover".equals(iq.getResult())){
                    	SparkToaster toaster = new SparkToaster();
                        toaster.setNotifyShowForever(false);
                        toaster.setDisplayTime(10000);
                        toaster.setBorder(BorderFactory.createBevelBorder(0));
                        toaster.setTitle(Res.getString("title.notification"));
                        toaster.setViewLabelString("");
                        //toaster.showToaster(iq.getTitle());
                        SpecialistQueueManager.getInstance().removeWhenLeave(iq.getSpjid());
                    	MessageCenterPanel.getInstance().removeJoinMessageItem(iq.getSpid(), iq.getSpjid());
                		JOptionPane.showMessageDialog(SparkManager.getMainWindow(), iq.getTitle());
                    }
                }
                catch (Exception e) {
                    Log.error(e);
                }
            }
        });
	}

	private class PollPacketListener implements PacketListener{

		@Override
		public void processPacket(Packet packet) {
			// TODO Auto-generated method stub
	        final SpecialistPollPacket iq = (SpecialistPollPacket)packet;
	        
	        String spjid = NetcallUtil.getBareJID(iq.getFrom());
	        String spid = iq.getSpid();
	        String sessionId = iq.getSessionId();
	        SparkToaster toaster = new SparkToaster();
	        toaster.setNotifyShowForever(true);
	        toaster.setToasterHeight(200);
	        toaster.setToasterWidth(300);
	        toaster.setViewLabelString("关闭");
            toaster.setHidable(true);
            toaster.setCustomAction(new AbstractAction() {
				
				private static final long serialVersionUID = 1L;

				@Override
				public void actionPerformed(ActionEvent e) {
					
				}
			});
            PollPanel poll = new PollPanel(spid,spjid,sessionId,toaster);
	        toaster.setDisplayTime(60*1000);
	        toaster.setNotifyShowForever(false);
	        toaster.showToaster("调查问卷", poll);
			// TODO Auto-generated method stub
//            ChatRoom chatRoom = SparkManager.getChatManager().createChatRoom(spjid, spid, spid);
//            chatRoom.getTranscriptWindow().addComponent(poll);
//            try {
//				Thread.sleep(500);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//            SparkManager.getChatManager().getChatContainer().activateChatRoom(chatRoom);
//            chatRoom.scrollToBottom();
		}
		
	}
	
	public byte[] encrypt(String message, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		return cipher.doFinal(message.getBytes("UTF-8"));
	}

	public String toHexString(byte b[]) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String plainText = Integer.toHexString(0xff & b[i]);
			if (plainText.length() < 2)
				plainText = "0" + plainText;
			hexString.append(plainText);
		}

		return hexString.toString();
	}
	
	public void addButoon(){
		CommandPanel cp = SparkManager.getWorkspace().getCommandPanel();
		if(ExpertManager.getInstance(SparkManager.getConnection()).isExpert()){
			//JMenuItem noteQuestionMenuItem = new JMenuItem("添加常见问题", SparkRes.getImageIcon(SparkRes.DOCUMENT_16x16));
			String iconURI ="images/question.gif";
			URL imageURL =ConsultantPlugin.class.getClassLoader().getResource(iconURI);
			final RolloverButton noteQuestionButton = new RolloverButton(new ImageIcon(imageURL));
			noteQuestionButton.setToolTipText("添加常见问题");
			noteQuestionButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {	
					try {
						String logonguid = toHexString(encrypt(
								LocalPreferences.getTokenKey(),
								SparkRes.getString("DESKEY")));
						String server = SettingsManager.getLocalPreferences().getKeyValue("channelname");
						String username = SettingsManager.getLocalPreferences().getKeyValue("userField"+server); 	
						String logonname = toHexString(encrypt(username,
									SparkRes.getString("DESKEY")));
						String servername = SettingsManager
								.getLocalPreferences().getServername();
						String returnurl = "http://www.netcall.cc/netcall/ProblemAdd.aspx";
						returnurl = toHexString(encrypt(returnurl,
								SparkRes.getString("DESKEY")));				 	
						String urlstring = "http://uia.netcall.cc:80/SetCookie.aspx?"+"&lg="+logonguid+"&ln="+logonname+"&ru="+returnurl;	
						BrowserLauncher.openURL(urlstring);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} 
				}
			});
	      //  SparkManager.getMainWindow().getMenuByName(Res.getString("menuitem.actions")).add(noteQuestionMenuItem);
		  cp.add(noteQuestionButton,1);
		}
		
		//CommandPanel cp = SparkManager.getWorkspace().getCommandPanel();
		String iconURI ="images/BBS.gif";
		URL imageURL =ConsultantPlugin.class.getClassLoader().getResource(iconURI);
		final RolloverButton netcallccButton = new RolloverButton(new ImageIcon(imageURL));
		netcallccButton.setToolTipText("登入论坛");
	//	CommandPanel cp = SparkManager.getWorkspace().getCommandPanel();
		cp.add(netcallccButton);
		final String bbsaddress = RestFulService.getBbsAddress();
		if(SettingsManager.getLocalPreferences().isPublicLogin()==false){
			if(bbsaddress.equals("")){
				netcallccButton.setVisible(false);
			}
		}
		
		netcallccButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					if (SettingsManager.getLocalPreferences().isPublicLogin()) {
						if(SettingsManager.getLocalPreferences().getKeyValue("userstatus").equals("UnAuth")){
							JOptionPane.showMessageDialog(new JFrame(),"您的身份还未认证,不允许登录在线论坛","提示信息",JOptionPane.PLAIN_MESSAGE);
						    return; 
						}
						if (LocalPreferences.getTokenKey() != null) {
							String logonguid = toHexString(encrypt(
									LocalPreferences.getTokenKey(),
									SparkRes.getString("DESKEY")));
						    String server = SettingsManager.getLocalPreferences().getKeyValue("channelname");
						    String username = SettingsManager.getLocalPreferences().getKeyValue("userField"+server); 	
							String logonname = toHexString(encrypt(username,
									SparkRes.getString("DESKEY")));
							String servername = SettingsManager
									.getLocalPreferences().getServername();
							String returnurl = "http://bbs.netcall.cc:8080/jsprunutf8/PostHtml.jsp";
							returnurl = toHexString(encrypt(returnurl,
									SparkRes.getString("DESKEY")));
//							BrowserLauncher
//									.openURL("http://"
//											+ servername
//											+ ":9090/plugins/uiauthentication/bbs?logonguid="
//											+ logonguid + "&logonname="
//											+ logonname + "&returnurl="
//											+ returnurl);
						    BrowserLauncher.openURL( "http://uia.netcall.cc:80/SetCookie.aspx?"+"&lg="+logonguid+"&ln="+logonname+"&ru="+returnurl);
							//BrowserLauncher.openURL( "http://10.0.18.19:82/SetCookie.aspx?"+"&lg="+logonguid+"&ln="+logonname+"&ru="+returnurl);
						} else {
							BrowserLauncher
									.openURL("http://bbs.netcall.cc:8080/jsprunutf8/index.jsp");
						}
					}else{
						//String bbsaddress = RestFulService.getBbsAddress();
						//if(bbsaddress.equals("")){
						//	netcallccButton.setVisible(false);
							//JOptionPane.showMessageDialog(new JFrame(),"请服务端配置论坛地址","提示信息",JOptionPane.PLAIN_MESSAGE);
						//}else{
							BrowserLauncher.openURL(bbsaddress);
						//}
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		RolloverButton channelchangebutton;		
		String iconuri;
		URL imageurl;
		if (SettingsManager.getLocalPreferences().isPublicLogin() ) {
			iconuri = "images/se.gif";
			imageurl = ConsultantPlugin.class.getClassLoader().getResource(
					iconuri);
			channelchangebutton = new RolloverButton(new ImageIcon(imageurl));
			channelchangebutton.setToolTipText("返回原服务器");
			if(SettingsManager.getLocalPreferences().getischannelchange()==true){
				cp.add(channelchangebutton);
			}
		}else{
			iconuri = "images/zx.gif";
			imageurl = ConsultantPlugin.class.getClassLoader().getResource(
					iconuri);
			channelchangebutton = new RolloverButton(new ImageIcon(imageurl));
			channelchangebutton.setToolTipText("新中大在线服务座席");
			cp.add(channelchangebutton);
		}
		
		final String changename = channelchangebutton.getToolTipText();
		channelchangebutton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub		
				if(changename.equals("新中大在线服务座席")){
					if(SettingsManager.getLocalPreferences().getKeyValue("passwordBox"+"新中大在线服务座席").equals("true")){				
						MainWindow.getInstance().changeChannel("新中大在线服务座席");
			            }else{			    
			               ChannelChangeDialog cdialog = new ChannelChangeDialog(MainWindow.getInstance(),"新中大在线服务座席");
			            }		
			
				}else{		
				   String oldchannelname = SettingsManager.getLocalPreferences().getKeyValue("oldchannelname");		
				   if(SettingsManager.getLocalPreferences().getKeyValue("passwordBox"+oldchannelname).equals("true")){
					   MainWindow.getInstance().changeChannel(oldchannelname);
				   }else{
					   ChannelChangeDialog cdialog = new ChannelChangeDialog(MainWindow.getInstance(),oldchannelname);
				   }
				}
				
			}
		});
		
		String iconUri = "images/w.gif";
		URL imageUrl = ConsultantPlugin.class.getClassLoader().getResource(iconUri);
		RolloverButton ccButton = new RolloverButton(new ImageIcon(imageUrl));
		ccButton.setToolTipText("在线服务网站");
		cp.add(ccButton);
		ccButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				try {
					if(SettingsManager.getLocalPreferences().isUiaEnabled()){
						if(SettingsManager.getLocalPreferences().isPublicLogin() && SettingsManager.getLocalPreferences().getKeyValue("userstatus").equals("UnAuth")){
							JOptionPane.showMessageDialog(new JFrame(),"您的身份还未认证,不允许登录在线服务网站","提示信息",JOptionPane.PLAIN_MESSAGE);
						    return; 
						}
						String logonguid = toHexString(encrypt(
								LocalPreferences.getTokenKey(),
								SparkRes.getString("DESKEY")));
					    String server = SettingsManager.getLocalPreferences().getKeyValue("channelname");
						String username = SettingsManager.getLocalPreferences().getKeyValue("userField"+server); 	
						String logonname = toHexString(encrypt(username,
									SparkRes.getString("DESKEY")));
						String servername = SettingsManager
								.getLocalPreferences().getServername();
					//	String returnurl = "http://10.0.19.27:86/index.aspx";
						String returnurl = "http://www.netcall.cc/index.aspx";
						returnurl = toHexString(encrypt(returnurl,
								SparkRes.getString("DESKEY")));				 	
					    String urlstring = "http://uia.netcall.cc:80/SetCookie.aspx?"+"&lg="+logonguid+"&ln="+logonname+"&ru="+returnurl;	
					  //  String urlstring = "http://10.0.18.19:82/SetCookie.aspx?"+"&lg="+logonguid+"&ln="+logonname+"&ru="+returnurl;	
					    BrowserLauncher.openURL(urlstring); 
					}else{
						BrowserLauncher.openURL("www.netcall.cc");
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
	
	}
	
	 public class ChannelChangeDialog extends JDialog{
	    	JLabel jl = new JLabel();
	    	JLabel userlabel = new JLabel();
	    	JLabel passwordlabel = new JLabel();
	    	JTextField userfield = new JTextField();
	    	JPasswordField passwordfield = new JPasswordField();
	    	JCheckBox passwordbox = new JCheckBox();
	    	JButton savebutton = new JButton();
	    	JButton cancelbutton = new JButton();
	    	JPanel jp = new JPanel();
	    	JPanel jpl = new JPanel();
	    	public ChannelChangeDialog(JFrame dialog,final String server){
	    		super(dialog);
	    		setTitle("切换频道");
	    		ResourceUtils.resLabel(jl,"正在切换到"+server+",请输入账号信息：");
	    		ResourceUtils.resLabel(userlabel,"用户名：");
	    		ResourceUtils.resLabel(passwordlabel,"密码：");
	    		ResourceUtils.resButton(passwordbox,"保存密码");
	    		ResourceUtils.resButton(savebutton,"确定");
	    		ResourceUtils.resButton(cancelbutton,"取消");
	    		setLayout(new BorderLayout());
	    		add(jl,BorderLayout.NORTH);
	    		add(jp,BorderLayout.CENTER);
	    		add(jpl,BorderLayout.SOUTH);
	    		jp.setLayout(new GridLayout(3,2));
	    		jp.add(userlabel);
	    		jp.add(passwordlabel);
	    		jp.add(userfield);
	    		jp.add(passwordfield);
	    		jp.add(passwordbox);
	    		jpl.setLayout(new FlowLayout());
	    		jpl.add(savebutton);
	    		jpl.add(cancelbutton);
	    		Point point= dialog.getLocation();
	    		setLocation((int)point.getX()-10, (int)point.getY()+200);
	    		//setLocationRelativeTo(dialog);
	 			setSize(300,150);
	 			setVisible(true);
	 			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	 			if(SettingsManager.getLocalPreferences().getKeyValue("userField"+server)!=null){
	 				userfield.setText(SettingsManager.getLocalPreferences().getKeyValue("userField"+server));
	 			}else{
	 				userfield.setText(SettingsManager.getLocalPreferences().getUsername());
	 			}
	 			
	 			savebutton.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent arg0) {
						// TODO Auto-generated method stub					
						SettingsManager.getLocalPreferences().setKeyValue("userField"+server, userfield.getText().trim());
						if(passwordbox.isSelected()) {
							SettingsManager.getLocalPreferences().setKeyValue("passwordBox" + server,"true");
							String password = new String(passwordfield.getPassword());
							try {
								password = Encryptor.encrypt(password);
								SettingsManager.getLocalPreferences().setKeyValue("passwordField"+server,password);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	 					}else{
	 						SettingsManager.getLocalPreferences().setKeyValue("passwordBox" + server,"false");
	 						String password = new String(passwordfield.getPassword());
							try {
								password = Encryptor.encrypt(password);
								SettingsManager.getLocalPreferences().setKeyValue("passwordField"+server,password);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	 					}
						SettingsManager.saveSettings();
						MainWindow.getInstance().changeChannel(server);
						dispose();
					}
				});
	    		
	    		cancelbutton.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent arg0) {
						dispose();
						
					}
				});
	    	}
	    	
	    }
}
